package com.talking.activities

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.gson.JsonParser
import com.parfoismeng.slidebacklib.registerSlideBack
import com.parfoismeng.slidebacklib.unregisterSlideBack
import com.talking.App
import com.talking.R
import com.talking.databinding.ActivityAccountBinding
import com.talking.util.Network
import com.talking.util.Tools
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.File
import java.io.IOException

class AccountActivity : AppCompatActivity() {
    private lateinit var filename: String
    private lateinit var launcher: ActivityResultLauncher<Intent>
    private lateinit var binding: ActivityAccountBinding
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivityAccountBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.accountAccountTv.setText(App.me.mail)
        binding.accountNicknameTv.setText(App.me.nickname)
        Glide.with(this).load(Network.BASE_URL+ App.me.iconUrl).apply(Tools.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.accountIcon)
        binding.accountModifyIcon.setOnClickListener { pick() }
        binding.accountIcon.setOnClickListener { pick() }
        binding.accountQrcode.setOnClickListener {launcher.launch(Intent(this,QrcodeActivity::class.java), ActivityOptionsCompat.makeSceneTransitionAnimation(this, binding.accountQrcodeIv, "qrcode")) }
        launcher = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK) {
                val uri = result.data!!.data
                val file = File(uri!!.path.toString())
                this.filename = file.name
                binding.accountIcon.setImageURI(uri)
                Glide.with(this).load(uri).apply(Tools.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.accountIcon)
                Network.upload("user/uploadIconByEmail/?mail="+App.me.mail, file, object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        e.printStackTrace()
                    }
                    override fun onResponse(call: Call, response: Response) {
                        runOnUiThread {
                            Tools.toast(JsonParser.parseString(response.body!!.string()).asJsonObject.get("msg").asString)
                        }
                    }
                })
            } else if (result.resultCode == ImagePicker.RESULT_ERROR) {
                Tools.toast(ImagePicker.getError(result.data))
            }
        }
        registerSlideBack { finish() }
    }
    @RequiresApi(Build.VERSION_CODES.M)
    private fun pick(){
        if (Tools.hasExternalStoragePermission(this)) {
            ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).saveDir(externalCacheDir.toString() + "icon").createIntent { intent: Intent? -> launcher.launch(intent) }
        } else {
            Tools.requestPermission(this)
        }
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (!App.me.nickname.equals(binding.accountNicknameTv.text.toString())){
                val map = HashMap<String, String>()
                map["mail"] = App.me.mail.toString()
                map["nickname"] = binding.accountNicknameTv.text.toString()
                Network.post(map, "user/changeNickname/") { call: Call ->
                    call.enqueue(object : Callback {
                        override fun onFailure(call: Call, e: IOException) {
                            e.printStackTrace()
                            runOnUiThread {
                                Tools.toast(e.message)
                            }
                        }
                        override fun onResponse(call: Call, response: Response) {
                            runOnUiThread{
                                val msg = JsonParser.parseString(response.body!!.string()).asJsonObject.get("msg").asString
                                Tools.toast(msg)
                                if (msg.equals("修改昵称成功")){
                                    finish()
                                }
                            }
                        }
                    })
                }
                return true
            }else{
                return super.onKeyDown(keyCode, event)
            }
        }else{
            return super.onKeyDown(keyCode, event)
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        unregisterSlideBack()
    }
}